<template>
  <div class="container">
    <el-container>
      <el-aside width="auto" class="aside">
        <el-menu
           class="el-menu-vertical-demo"
           background-color="#333744"
            text-color="#fff"
            :default-active="activeIndex"
            active-text-color="#6cb2fd"
            :collapse="!isCollapse"
            unique-opened
        >
          <el-menu-item v-for="item in noChildMenu" :key="item.id" :index="item.path" @click="addTab(item)">
             <el-icon><component :is="item.icon"></component></el-icon>
             <template #title>{{ $t(item.title) }}</template>
          </el-menu-item>
          <el-sub-menu v-for="item in hasChildMenu" :key="item.id" :index="String(item.id)">
             <template #title>
                <el-icon><component :is="item.icon"></component></el-icon>
                <span>{{ $t(item.title) }} </span>
             </template>
             <el-menu-item v-for="e in item.children" :key="e.id" :index="e.path" @click="addTab(e)">
                  <el-icon>
                    <component :is="e.icon"></component>
                  </el-icon>
                  <span slot="title">{{ $t(e.title) }}</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header class="normal-header">
          <div class="header-left">
            <el-button icon="Menu" @click="toggleCollpase"></el-button>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="e in titleList" :key="e.path" @click="handleBreadcrumbClick(e)">{{ $t(e.title) }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-right">
            <div class="info">
              <template v-if="indexDbNum > 0">
                <el-badge :value="indexDbNum" @click="openErrorList">
                  <el-icon size="24px"><BellFilled /></el-icon>
                </el-badge>
              </template>
              <template v-else>
                <el-icon size="24px" @click="noError"><BellFilled /></el-icon>
              </template>
            </div>
           
            <div class="exit">
              <el-button @click="exit">
                <template #icon>
                  <i style="font-size: 18px;" class="iconfont icon-tuichu"></i>
                </template>
                 退出
              </el-button>
            </div>
          </div>
        </el-header>
        <el-main class="main-content">
          <!-- tab列表 -->
          <ul class="tabList">
            <div class="tab" v-for="e in tabList" :to="e.path" :kye="e.id">
              <el-tag 
                type="info"
                size="large" 
                :class="[e.isChecked? 'btn_active': 'btn']"
                :closable="e.id !== 1"
                @click="checkTag(e.id)"
                @close="closeTab(e)"
              >{{ $t(e.name) }}</el-tag>
            </div>
          </ul>
          <!-- 路由展示页面 -->
          <div class="roterView">
            <router-view #default="{ Component }">
              <Suspense>
                <template #default>
                  <keep-alive :include="keepAliveComponents">
                    <component :is="Component" />
                  </keep-alive>
                </template>
                <template #fallback>
                  <div class="loading-container">
                    <el-icon class="is-loading" size="30px"><Loading /></el-icon>
                  </div>
                </template>
              </Suspense>
            </router-view>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { ref,computed, type Ref, onMounted, onUnmounted } from 'vue'
import {useRouter} from "vue-router";
import { ElMessage, ElIcon } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
let isCollapse = ref<boolean>(true) // 菜单栏是否展开了
let router = useRouter()  // 路由对象

const keepAliveComponents = computed(() => {
  // 从 tabList 中提取需要缓存的组件名
  // 注意：这里的 name 应该与组件定义中的 name 一致
  return tabList.value.map(tab => {
    // 从路由路径中推断组件名，例如 /admin/data -> Data
    const pathParts = tab.path.split('/');
    const componentName = pathParts[pathParts.length - 1];
    if (componentName === 'admin' || componentName === '') {
        return 'AdminIndex';
    }
    return componentName.charAt(0).toUpperCase() + componentName.slice(1);
  });
});

const toggleCollpase = () => {
   isCollapse.value = !isCollapse.value
}
let activeIndex = computed(() => {
  return router.currentRoute.value.fullPath
})

// 监听窗口大小变化
const handleResize = () => {
  isCollapse.value = window.innerWidth >= 1200
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
  handleResize() // 初始化
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

/**右边工具栏 */
import { moduleStore } from '../../store/module';
import { storeToRefs } from 'pinia';

let module_store = moduleStore()
let {isFullscreen} = storeToRefs(module_store)
const taggleFullscreen = () => {
     if (!isFullscreen.value) {
        launchFullscreen(document.documentElement)
        isFullscreen.value = true
     } else {
         exitFullscreen()
         isFullscreen.value = false
     }
}
/* 菜单栏的渲染*/
import {menuList} from "../../local/menuList"
let noChildMenu = menuList.filter((item:any) => !item.hasOwnProperty("children"))
let hasChildMenu = menuList.filter((item:any) => item.hasOwnProperty("children"))

/**tab切换功能实现 */
// 导入tab模块
import { tabStore } from '../../store/tab'
import type { ITabStoreState } from '../../store/tab'; // Import the interface for type hinting
let tab_store = tabStore()
import Tab from '../../utils/tab'
import { storeToRefs } from 'pinia';
let { tabList, titleList } = storeToRefs(tab_store) as unknown as { tabList: Ref<ITabStoreState['tabList']>, titleList: Ref<ITabStoreState['titleList']> }
// 添加模块 (点击路由) => 添加绑定事件
const addTab = (obj: any) => {
    let tab = new Tab(obj.id,obj.title,obj.path,obj.router)
    tab_store.addTab(tab)
}
// 点击面包屑导航
const handleBreadcrumbClick = (item: any) => {
  if (item.path) {
    router.push(item.path);
  }
}
// 切换标签
const checkTag = (id:number) => {
  tab_store.checkTab(id)
}
// 关闭标签
const closeTab = (e:any) => {
   tab_store.deleteTab(e)
}
// 报警未读消息
import { userStore } from '../../store/user';
let store = userStore()
let {indexDbNum,errList} = storeToRefs(store)
import { adminStore } from '../../store/admin';
let admin_store = adminStore()
let { isOpenDrawer } = storeToRefs(admin_store)
import { getCurrentInstance, type ComponentInternalInstance } from 'vue';
const { proxy } = getCurrentInstance() as { proxy: ComponentInternalInstance['proxy'] | null }
import indexDb from '../../local/indexDb';
// 打开报警列表
const openErrorList = async () => {
  isOpenDrawer.value = true
  let result:any = await indexDb.getAllData()
  if (proxy) {
    errList.value = result.slice(0,10)
  }
}
// 提醒用户没有报警
const noError = () => {
  ElMessage.info("没有报警信息")
}
// 退出后台
const exit = () => {
  router.push("/")
  tabList.value = [{
    id: 1,
    path: "/admin",
    name: "首页",
    isChecked: true,
    router: [
        {title: "首页",path: "/admin"}
    ]
  }]
}

/**中英文切换 */
import { useConfigStore } from '../../store/config';
let config_store = useConfigStore()
let { language } = storeToRefs(config_store)

const setLanguage = (lang:string) => {
  config_store.setLanguage(lang)
}

function launchFullscreen(element: HTMLElement) {
 if((element as any).requestFullscreen) {
  (element as any).requestFullscreen();
 } else if((element as any).mozRequestFullScreen) {
  (element as any).mozRequestFullScreen();
 } else if((element as any).webkitRequestFullscreen) {
  (element as any).webkitRequestFullscreen();
 } else if((element as any).msRequestFullscreen) {
  (element as any).msRequestFullscreen();
 }
}

function exitFullscreen() {
 if((document as any).exitFullscreen) {
  (document as any).exitFullscreen();
 } else if((document as any).mozCancelFullScreen) {
  (document as any).mozCancelFullScreen();
 } else if((document as any).webkitExitFullscreen) {
  (document as any).webkitExitFullscreen();
 }
}
</script>

<style lang="less" scoped>
 .el-sub-menu__title span {
      margin-left: 15px;
 }
  
    /**菜单属性 */
   .el-menu {
      height: 100%!important;
      background-color: #304156;
      border-right: none;
      overflow-x: visible;
      .el-menu-item {
         .el-icon {
          margin-right: 25px;
         }
      }
   }

   /* 保证菜单在展开过程中，文本不被裁切 */
   .el-menu-item,
   .el-sub-menu__title {
     overflow: visible !important;
   }

   .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 220PX;
   }

   /**按钮的激活属性和正常属性 */
   .btn {
     color: #000;
     border: none;
     border:none;
     padding: 7px 20px;
     text-decoration: none;
   }
   .btn_active {
     background-color: #42b983;
     .btn;
     color: #fff;
     &::before {
      content: "";
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background-color: #fff;
      margin-right: 5px;
     }
   }
   
  .container {
    background-color: #eff1f4;
    width: 100%;
    height: 100%;
    .el-container {
      height: 100%;
      .el-side {
        width: 200px;
      }
      .el-main {
        padding: 0;
        display: flex;
        flex-direction: column;
        height: calc(100vh - 73px); /* 减去 header 的高度 */

        .tabList {
          flex-shrink: 0; /* 防止 tabList 被压缩 */
          height: 65px;
          background-color: #fff;
          border-top: 2px solid silver;
          border-bottom: 2px solid silver;
          display: flex;
          align-items: center;
          padding: 10px 20px;
          .tab {
            margin-right: 20px;
          }
        }

        .roterView {
          flex-grow: 1; /* 占据剩余空间 */
          overflow: auto; /* 如果内容溢出，则显示滚动条 */
          width: 100%;
          background: #fff;
          position: relative; /* 为loading-container定位 */
        }
      }
    }
  }

  .loading-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /**中文切换 */
  .taggleZn {
    padding-left: 3px;
    padding-right: 20px;
  }

  .normal-header {
    height: 73px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24px;
  }
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  .main-content {
    margin-top: 3px;
  }
  .el-aside {
    position: relative;
    z-index: 10;
  }
  .el-container, .el-main, .el-aside {
    height: 100vh;
  }
</style>